import React, { Component } from "react";
import { Forms } from "@/components/Forms/forms";
import {
  Table,
  Modal,
  message,
  Pagination,
  Input,
  Select,
  Form,
  DatePicker
} from "antd";
import Request, { Delete, Get, Download } from "@/utils/request";
import moment from "moment";
import styles from "./index.less";
import AddFocusNews from "@/components/mainPageEdit/focusNews/addFocusNEws";
import { setCallBack, showBack } from "@/layouts/BasicLayout";
import IconFont from "@/components/Iconfont/index";
let container = null;
const btns = [
  {
    label: "导出",
    props: {
      className: "error_btn",
      onClick: () => {
        container.export();
      }
    }
  }
];
const list = [
  {
    input: true,
    key: "k",
    placeholder: "关键字"
  },
  // {
  //   select: true,
  //   key: 'states',
  //   defaultValue:'2',
  //   options:[
  //     {label:'未领取',value:'0'},
  //     {label:"已领取",value:"1"},
  //     {label:'全部',value:'2'}
  //   ]
  // },
  {
    select: true,
    key: "prize_states",
    defaultValue: "2",
    options: [
      { label: "未使用", value: "0" },
      { label: "已使用", value: "1" },
      { label: "全部", value: "2" }
    ]
  }
];
const columns = [
  {
    title: "手机号",
    dataIndex: "phone",
    key: "phone"
  },
  {
    title: "奖品",
    dataIndex: "prize",
    key: "prize",
    render: (text, record) => {
      return <span>{record.prize.name}</span>;
    }
  },
  {
    title: "奖券",
    dataIndex: "serial_no",
    key: "serial_no",
    render: (text, record) => {
      return <span>{record.serial_no}</span>;
    }
  },

  {
    title: "抽奖时间",
    dataIndex: "draw_date",
    key: "draw_date",
    render: (text, record) => {
      return (
        <span>
          {record.draw_time == 0
            ? ""
            : moment(record.draw_time).format("YYYY-MM-DD HH:mm")}
        </span>
      );
    }
  },
  {
    title: "使用情况",
    dataIndex: "prize_state",
    key: "prize_state"
  },
  {
    title: "使用时间",
    dataIndex: "prize_time",
    key: "prize_time",
    render: (text, record) => {
      return (
        <span>
          {record.prize_time == 0
            ? ""
            : moment(record.prize_time).format("YYYY-MM-DD")}
        </span>
      );
    }
  }
];
class DataPage extends React.Component {
  state = {
    list: [],
    id: "",
    edit: false,
    phone: "",
    loading: false,
    offset: 0,
    count: 10,
    total: 0,
    date: "",
    checkedIds: [],
    isDetail: false,
    detailId: "",
    k: "",
    dataexportvisible: false,
    states: "2", //全部
    prize_states: "2" //全部
  };
  componentDidMount() {
    container = this;
    this.getList();
  }
  onCurrentChange = offset => {
    this.setState(
      {
        offset: offset - 1
      },
      () => {
        this.getList();
      }
    );
  };
  export = () => {
    Download("/psy/mss/lottery/export", {
      states: ["未领取", "已领取"],
      prize_states: ["未使用", "已使用"],
      draw_zones: ["武汉SKP"],
      project_id:'6686b0edd2e144041483587b'
    }).then(res => {});
  };
  exportFromData = () => {
    Download("/psy/mss/lottery/export", {
      states: ["未领取", "已领取"],
      prize_states: ["未使用", "已使用"],
      draw_zones: ["武汉SKP"],
      draw_start_date: this.state.date,
      draw_end_date: this.state.date,
      project_id:'6686b0edd2e144041483587b'
    }).then(res => {
      this.setState({
        dataexportvisible: false
      });
    });
  };
  onSearch(values) {
    console.log(values);
    var k = "";
    var states = "2";
    var prize_states = "2";
    if (values["k"]) {
      k = values["k"];
    }
    if (values["states"]) {
      states = values["states"];
    }
    if (values["prize_states"]) {
      prize_states = values["prize_states"];
    }
    container.setState(
      {
        k: k,
        states: states,
        prize_states: prize_states,
       
      },
      () => {
        container.getList();
      }
    );
  }
  getList() {
    this.setState({
      loading: true
    });
    let statesObj = {
      "0": ["未领取"],
      "1": ["已领取"],
      "2": ["未领取", "已领取"]
    };
    let prizeStatesObj = {
      "0": ["未使用"],
      "1": ["已使用"],
      "2": ["未使用", "已使用"]
    };
    Request("/psy/mss/lottery/query", {
      k: this.state.k,
      phones: this.state.phone == "" ? [] : [this.state.phone],
      offset: this.state.offset * this.state.count,
      count: this.state.count,
      states: statesObj[this.state.states],
      prize_states: prizeStatesObj[this.state.prize_states],
      project_id:'6686b0edd2e144041483587b'
    }).then(res => {
      this.setState({
        loading: false,
        list: res.data.data,
        total: res.data.total_count
      });
    });
  }
  batchDelete() {
    if (container.state.checkedIds.length == 0) {
      message.error("至少选择一个");
      return;
    }
    Modal.confirm({
      title: "确认删除？",
      okText: "确认",
      cancelText: "取消",
      onOk() {
        console.log(container.state.checkedIds);
        // Delete('/psy/portlet/article/'+id,{}).then((res) => {
        //   container.getList();
        // })
      },
      onCancel() {
        console.log("Cancel");
      }
    });
  }
  delete(id) {
    Modal.confirm({
      title: "确认删除？",
      okText: "确认",
      cancelText: "取消",
      onOk() {
        Delete("/psy/portlet/article/del/" + id, {}).then(res => {
          container.getList();
        });
      },
      onCancel() {
        console.log("Cancel");
      }
    });
  }
  callBack() {
    this.setState(
      {
        isDetail: false
      },
      () => {
        this.getList();
      }
    );
  }
  onShowSizeChange(size) {
    console.log(size);
  }
  render() {
    const { edit, total, isDetail } = this.state;
    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        const arr = [];
        selectedRows.map(e => {
          arr.push(e.id);
        });
        this.setState({
          checkedIds: arr
        });
      },
      getCheckboxProps: record => {
        return {
          disabled: false, // Column configuration not to be checked
          name: record.name,
          checked:
            this.state.checkedIds.indexOf(record.id) !== -1 ? true : false
        };
      }
    };
    return (
      <div>
        <div className="module-title">{this.props.route.name}</div>
        {isDetail ? (
          <QADetail
            type={1}
            callBack={() => this.callBack()}
            id={this.state.detailId}
          />
        ) : (
          <div>
            {edit ? (
              <div className={styles.addNewsContainer}>
                <AddFocusNews
                  nocover_image={true}
                  id={this.state.id}
                  page_id={this.props.match.params.id}
                  goBack={() =>
                    this.setState(
                      {
                        edit: false
                      },
                      () => {
                        this.getList();
                      }
                    )
                  }
                />
              </div>
            ) : (
              <div>
                <form className="ant-legacy-form ant-legacy-form-inline forms_">
                  <div className="left">
                    <div className="ant-row ant-legacy-form-item">
                      <Input
                        value={this.state.phone}
                        placeholder="请输入手机号"
                        onChange={e => {
                          this.setState({
                            phone: e.target.value
                          });
                        }}
                      />
                    </div>
                    <div className="ant-row ant-legacy-form-item">
                      <Select
                        value={this.state.prize_states}
                        onChange={val => {
                          this.setState({
                            prize_states: val
                          });
                        }}
                      >
                        <Option value="0">未使用</Option>
                        <Option value="1">已使用</Option>
                        <Option value="2">全部</Option>
                      </Select>
                    </div>
                    <div className="ant-row ant-legacy-form-item">
                      <div
                        className="ant-btn success_btn"
                        onClick={() => {
                          this.setState(
                            {
                              offset: 0
                            },
                            () => {
                              container.getList();
                            }
                          );
                        }}
                        style={{ position: "relative", top: "3px" }}
                      >
                        查询
                      </div>
                    </div>
                  </div>
                  <div className="right">
                    <div
                      className="ant-btn error_btn"
                      onClick={() => this.export()}
                      style={{ marginRight: "15px" }}
                    >
                      全部导出
                    </div>
                    <div
                      className="ant-btn error_btn"
                      onClick={() =>
                        this.setState({
                          dataexportvisible: true
                        })
                      }
                    >
                      按日期导出
                    </div>
                  </div>
                </form>
                <div className="table-box">
                  <Table
                    pagination={{
                      current: this.state.offset + 1,
                      total: this.state.total,
                      onChange: this.onCurrentChange,
                      pageSize: this.state.count,
                      showSizeChanger: false
                    }}
                    loading={this.state.loading}
                    dataSource={this.state.list}
                    columns={columns}
                  />
                </div>
              </div>
            )}
          </div>
        )}
        <Modal
          title="导出"
          visible={this.state.dataexportvisible}
          onOk={this.exportFromData}
          onCancel={() =>
            this.setState({
              dataexportvisible: false
            })
          }
        >
          <DatePicker
            value={this.state.date ? moment(this.state.date) : ""}
            onChange={(date, datestr) => {
              this.setState({
                date: datestr
              });
            }}
          />
        </Modal>
      </div>
    );
  }
}

class QADetail extends Component {
  state = {
    dataInfo: null,
    replyList: [],
    offset: 0,
    count: 10,
    total_count: 0
  };
  componentDidMount() {
    showBack(true);
    setCallBack(() => {
      this.props.callBack();
    });
    document.getElementById("layoutContent").className = styles.layout;
    this.getQaDetail();
    this.getReplyList();
  }
  componentWillUnmount() {
    showBack(false);
    document.getElementById("layoutContent").className =
      "antd-pro-layouts-basic-layout-contentWrap";
  }
  // 获取详情
  getQaDetail() {
    var url =
      this.props.type == 1
        ? "/psy/portlet/article/info/"
        : "/psy/portlet/comment/get/";
    Get(url + this.props.id, {}).then(res => {
      this.setState({
        dataInfo: res.data
      });
    });
  }
  // 获取回复
  getReplyList() {
    Request("/psy/portlet/comment/query", {
      k: "",
      offset: this.state.offset * this.state.count,
      count: this.state.count,
      target_type: this.props.type == 1 ? "question" : "comment",
      target_id: this.props.id
    }).then(res => {
      this.setState({
        loading: false,
        replyList: res.data.data ? res.data.data : [],
        total: res.data.total_count
      });
    });
  }
  delete(id) {
    const _this = this;
    Modal.confirm({
      title: "确认删除？",
      okText: "确认",
      cancelText: "取消",
      onOk() {
        const url =
          _this.props.type == 1
            ? "/psy/portlet/article/del/"
            : "/psy/portlet/comment/manage/";

        Delete(url + id, {}).then(res => {
          _this.props.callBack();
        });
      },
      onCancel() {
        console.log("Cancel");
      }
    });
  }
  commentdelete(id) {
    const _this = this;
    Modal.confirm({
      title: "确认删除？",
      okText: "确认",
      cancelText: "取消",
      onOk() {
        Delete("/psy/portlet/comment/manage/" + id, {}).then(res => {
          _this.getReplyList();
        });
      },
      onCancel() {
        console.log("Cancel");
      }
    });
  }
  onCurrentChange(offset) {
    this.setState(
      {
        offset: offset - 1
      },
      () => {
        this.getReplyList();
      }
    );
  }
  render() {
    const { replyList, dataInfo } = this.state;
    return (
      <div>
        {dataInfo ? (
          <div className={styles.article}>
            <div className={styles.articleimg}>
              {this.props.type == 1 ? (
                <img
                  src={dataInfo.author.avatar ? dataInfo.author.avatar : ""}
                />
              ) : (
                <img src={dataInfo.user.avatar ? dataInfo.user.avatar : ""} />
              )}
            </div>
            <div className={styles.articleinfo}>
              <div className={styles.articletitle}>
                <div className={styles.articletitles}>
                  <div>
                    {this.props.type == 1 ? dataInfo.title : dataInfo.user.name}
                  </div>
                  <div className={styles.articleDate}>
                    {moment(dataInfo.pubdate).format("YYYY-MM-DD HH:mm:ss")}
                    <IconFont
                      type="iconyuedu"
                      style={{ margin: "0 5px 0 24px" }}
                    />
                    {dataInfo.read_times}
                  </div>
                </div>
                <div className={styles.articleReply}>
                  <div
                    style={{ marginRight: "5px" }}
                    className={"error_btn ant-btn " + styles.replybtn}
                  >
                    下架
                  </div>
                  <div
                    onClick={() => this.delete(dataInfo.id)}
                    className={"error_btn ant-btn " + styles.replybtn}
                  >
                    删除
                  </div>
                </div>
              </div>
              <div className={styles.articlecount}>{dataInfo.content}</div>
              <div className={styles.iconFontWrap}>
                <IconFont type="iconxingzhuang1" />
                <span className={styles.iconFontCount}>
                  {dataInfo.thumbs_up}
                </span>
                <IconFont type="iconxingzhuang" />
                <span className={styles.iconFontCount}>
                  {dataInfo.comment_times}
                </span>
              </div>
            </div>
          </div>
        ) : (
          <div></div>
        )}
        {replyList.length > 0 && <div className={styles.splitLine}></div>}

        {replyList.map((e, i) => {
          return (
            <div className={styles.article}>
              <div className={styles.articleimg}>
                <img src={e.user.avatar ? e.user.avatar : ""} />
              </div>
              <div className={styles.articleinfo}>
                <div className={styles.articletitle}>
                  <div className={styles.articletitles}>
                    <div>{e.user.name}</div>
                    <div className={styles.articleDate}>
                      {moment(e.pubdate).format("YYYY-MM-DD HH:mm:ss")}
                    </div>
                  </div>
                  <div className={styles.articleReply}>
                    <div
                      style={{ marginRight: "5px" }}
                      className={"error_btn ant-btn " + styles.replybtn}
                    >
                      下架
                    </div>
                    <div
                      onClick={() => this.commentdelete(e.id)}
                      className={"error_btn ant-btn " + styles.replybtn}
                    >
                      删除
                    </div>
                  </div>
                </div>
                <div className={styles.articlecount}>{e.content}</div>
                <div className={styles.iconFontWrap}>
                  <IconFont type="iconxingzhuang1" />
                  <span className={styles.iconFontCount}>{e.thumbs_up}</span>
                  <IconFont type="iconxingzhuang" />
                  <span className={styles.iconFontCount}>
                    {e.comment_times}
                  </span>
                </div>
              </div>
            </div>
          );
        })}
        {this.state.total > 0 && (
          <div className={styles.Pagination}>
            <Pagination
              onChange={this.onCurrentChange}
              current={this.state.offset + 1}
              total={this.state.total}
              pageSize={this.state.count}
            />
          </div>
        )}
      </div>
    );
  }
}

export { QADetail };
export default DataPage;
